

package com.love.cloud.common.core.handle;

import com.love.cloud.common.core.exception.AuthException;
import com.love.cloud.common.core.exception.BusinessException;
import com.love.cloud.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 全局异常处理器结合sentinel 全局异常处理器不能作用在 oauth server https://gitee.com/log4j/pig/issues/I1M2TJ
 * </p>
 *
 * @author lengleng
 * @date 2020-06-29
 */
@Slf4j
@RestControllerAdvice
public class GlobalBizExceptionHandler {

	/**
	 * 全局异常.
	 * @param e the e
	 * @return R
	 */
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public R handleGlobalException(Exception e) {
		log.error("全局异常信息 ex={}", e.getMessage(), e);
		return R.failed(e.getLocalizedMessage());
	}

	/**
	 * validation Exception (以form-data形式传参)
	 * @param exception
	 * @return R
	 */
	@ExceptionHandler({ BindException.class })
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R bindExceptionHandler(BindException exception) {
		List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
		log.warn("参数绑定异常,ex = {}", fieldErrors.get(0).getDefaultMessage());
		return R.failed(fieldErrors.get(0).getDefaultMessage());
	}

	/**
	 * 处理运行时异常
	 */
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(Throwable.class)
	public R handleThrowable(Throwable e, HttpServletRequest request) {
		//TODO 运行是异常，可以在这里记录，用于发异常邮件通知
		log.error("URL:{} ,系统异常: ",request.getRequestURI(), e);
		return R.failed(e.getLocalizedMessage());
	}

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(BusinessException.class)
	public R handleBusinessException(BusinessException e, HttpServletRequest request) {
		return R.failed(e.getCode(),e.getMessage());
	}

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(AuthException.class)
	public R handleAuthException(AuthException e, HttpServletRequest request) {
		return R.failed(e.getCode(),e.getMessage());
	}

	/**
	 * validator 统一异常封装
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
		String msgs = this.handle(e.getBindingResult().getFieldErrors());
		log.warn("URL:{} ,参数校验异常:{}", request.getRequestURI(),msgs);
		return R.failed(msgs);
	}

	private String handle(List<FieldError> fieldErrors) {
		StringBuilder sb = new StringBuilder();
		for (FieldError obj : fieldErrors) {
			sb.append(obj.getField());
			sb.append("=[");
			sb.append(obj.getDefaultMessage());
			sb.append("]  ");
		}
		return sb.toString();
	}

	/**
	 * Assert的异常统一封装
	 */
	@ExceptionHandler(IllegalArgumentException.class)
	public R illegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
		log.warn("URL:{} ,业务校验异常:{}", request.getRequestURI(),e);
		return R.failed(e.getMessage());
	}

}
